import React, { Component } from 'react';
import { connect } from 'umi';
import { Bar, Column } from '@antv/g2plot';
import { Chart, registerShape } from '@antv/g2';
import "./dashboard.less"
import { ConnectState } from "@/models/connect";
import $ from 'jquery'

import * as echarts from 'echarts';
// import { Scene, PointLayer } from '@antv/l7';
// import { CountryLayer, ProvinceLayer } from '@antv/l7-district';
// import { Mapbox, GaodeMap } from '@antv/l7-maps';

interface DashboardWorkplaceState {
  currentFilter: number,
  mapFrontSize: string,
  font: object
}

interface IDraw {
  id: string;
  title: string;
  className: string;
}

class DashboardWorkplace extends Component<any, DashboardWorkplaceState> {

  constructor(props: any) {
    super(props);
    // this.state = { currentFilter: 1,mapFrontSize:"0.8rem" }
    // let chinaMap;
  }

  reload = () => {
    let domWidth = $("#home-back").width();
    if (domWidth) {
      let scaling = (domWidth / 1500);
      // console.log("缩放比例", scaling * 1080)
      $("#home-back").css("height", `${scaling * 1080}px`);
    }

    // console.log("缩放比", this.GetScreenZoom());
    /*less.modifyVars({
      '@small': `${0.7 / window.devicePixelRatio}`,
      '@big': `${1 / window.devicePixelRatio}`
    });*/
    $("a.l7-ctrl-logo").css("display", "none");
    // const map = $('#map');

    // $('#map>div:first-child>canvas').css({ 'width': `${map.width()}px`, 'height': `${map.height()}` })
    //$('#map>div:first-child>div:first-child>svg:first-child>:nth-child(2) text').css({ 'width': `${map.width()}px`, 'height': `${map.height()}` })
    // $('#map>div:first-child').css({'width':`${map.width()}px`,'height':`${map.height()}`})
    // $("#map text").css("font","20px \"Microsoft YaHei\"");
    /*  setTimeout(() => {
        console.log( $("#map svg g text").css("font","20px \"Microsoft YaHei\""));
     }, 1000); */
    //  this.setState({font:{size:20}})
  }

  GetScreenZoom() {

    var ratio = 0

    if (window.devicePixelRatio !== undefined) {
      ratio = window.devicePixelRatio;
    }

    else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
      ratio = window.outerWidth / window.innerWidth;
    }

    if (ratio) {
      ratio = Math.round(ratio * 100);
    }
    return ratio;


  }

  componentDidMount() {
    //this.courseCount();
    let domWidth = $("#home-back").width();
    if (domWidth) {
      let scaling = (domWidth / 1500);
      $("#home-back").css("height", `${scaling * 1080}px`);
    }
    /*less.modifyVars({
      '@small': `${0.7 / window.devicePixelRatio}`,
      '@big': `${1 / window.devicePixelRatio}`
    });*/
    this.visitTrend();
    this.courseTop();
    this.courseCountOther();
    this.courseHeat();
    this.courseUtilization();
    this.innerProductGraph();
    const chinaMap = this.DrawChinaDistrbutionMap();

    $("a.l7-ctrl-logo").css("display", "none")
    // window.onresize = function(){
    //     if(normalWidth>window.innerWidth||h< normalHeight.innerHeight){
    //         location.reload();
    //     }
    // }

    // console.log( $("#home-back canvas"));
    // var ctx = document.getElementById("canvas").getContext("2d");
    let size=12;

    this.reload();
    // const zoom = this.GetScreenZoom();
    chinaMap?.on('rendered', function () {
      $("#map svg g text").css("font", `${size}`+"px \"Microsoft YaHei\"")
    });
    window.onresize = () => {
    if(this.GetScreenZoom()==100){
      size=12;
    }else if(this.GetScreenZoom()<100){
      size=10*(1+(100-this.GetScreenZoom())*(100-this.GetScreenZoom())/1000)
    }else{
      size=10*(0.1+1+(100-this.GetScreenZoom())/400)
    }
      this.reload();
      chinaMap.resize();
    }

  }

  courseCountOther() {
    const data = [
      { type: '计算机类', value: 27 },
      { type: '数学类', value: 25 },
      { type: '化学类', value: 18 },
      { type: '物理类', value: 15 },
      { type: '食品类', value: 10 },
      { type: '地质类', value: 5 },
    ];

    let max = 0;
    data.forEach(function (obj) {
      if (obj.value > max) {
        max = obj.value;
      }
    });

    // 自定义 other 的图形，增加两条线
    registerShape('interval', 'slice-shape', {
      draw(cfg, container) {
        const points: any = cfg.points;
        const origin: any = cfg.data;
        const percent = origin.value / max;
        const xWidth = points[2].x - points[1].x;
        const width = xWidth * percent;
        let path = [];
        path.push(['M', points[0].x, points[0].y]);
        path.push(['L', points[1].x, points[1].y]);
        path.push(['L', points[0].x + width, points[2].y]);
        path.push(['L', points[0].x + width, points[3].y]);
        path.push('Z');
        // @ts-ignore
        path = this.parsePath(path);
        return container.addShape('path', {
          attrs: {
            fill: cfg.color,
            path,
          },
        });
      },
    });

    const chart = new Chart({
      container: 'container16',
      autoFit: true,
      height: 270,
    });

    chart.coordinate('theta', {
      radius: 0.8,
    });

    chart.data(data);

    chart.tooltip({
      showTitle: false,
      showMarkers: false,
    });

    chart
      .interval()
      .adjust('stack')
      .position('value')
      .color('type')
      .shape('slice-shape')
      //.label('type');
      .label('type', {
        offset: '-40%',
        layout: {
          type: 'limit-in-shape',
        },
        background: {
          style: {
            fill: '#000',
            // @ts-ignore
            fillOpacity: '0',
            radius: 2,
          },
          padding: 2,
        },
      });

    chart.interaction('element-active');

    chart.render();
  }


  // //课程数量
  // courseCount() {
  //   const data = [
  //     { type: '物理类', value: 27 },
  //     { type: '化学类', value: 21 },
  //     { type: '生物类', value: 21 },
  //     { type: '文学类', value: 45 },
  //     { type: '计算机类', value: 15 },
  //   ];
  //   const piePlot = new Pie('container12', {
  //     appendPadding: 0,
  //     data,
  //     angleField: 'value',
  //     colorField: 'type',
  //     radius: 1.0,
  //     legend: {
  //       layout: 'horizontal',
  //       position: 'bottom'
  //     },
  //     label: {
  //       type: 'inner',
  //       offset: '30%',
  //       content: '{percentage}',
  //       style: {
  //         fill: '#fff',
  //         fontSize: 10,
  //         textAlign: 'center',
  //       },
  //     },
  //     interactions: [{ type: 'element-active' }],
  //   });
  //   piePlot.render();
  // }


  //访问趋势
  visitTrend() {
    const data = [
      { name: '男', 时间: '五天前', 访问量: 13.3, },
      { name: '男', 时间: '四天前', 访问量: 10.3, },
      { name: '男', 时间: '三天前', 访问量: 15.3, },
      { name: '男', 时间: '前天', 访问量: 18.9, },
      { name: '男', 时间: '昨天', 访问量: 28.8, },
      { name: '男', 时间: '今天', 访问量: 39.3, },
      { name: '女', 时间: '五天前', 访问量: 7.1, },
      { name: '女', 时间: '四天前', 访问量: 5.1, },
      { name: '女', 时间: '三天前', 访问量: 10.1, },
      { name: '女', 时间: '前天', 访问量: 12.4, },
      { name: '女', 时间: '昨天', 访问量: 23.2, },
      { name: '女', 时间: '今天', 访问量: 34.5, },
    ];

    const stackedColumnPlot = new Column('container3', {
      data,
      isGroup: true,
      xField: '时间',
      yField: '访问量',
      seriesField: 'name',
      /** 设置颜色 */
      color: ['#2C96FC', '#FED825'],
      /** 设置间距 */
      // marginRatio: 0.1,
      label: {
        // 可手动配置 label 数据标签位置
        position: 'middle', // 'top', 'middle', 'bottom'
        // 可配置附加的布局方法
        layout: [
          // 柱形图数据标签位置自动调整
          { type: 'interval-adjust-position' },
          // 数据标签文颜色自动调整
          { type: 'adjust-color' },
        ],
      },
    });

    stackedColumnPlot.render();
  }

  courseTop() {
    const data = [
      { name: '计算思维', value: 88 },
      { name: '生物化学', value: 82 },
      { name: '畜产食品工艺学', value: 61 },
      { name: '计算机实验箱', value: 50 },
      { name: '光折射的隐身原理', value: 43 },
    ];

    const bar = new Bar("container11", {
      data,
      xField: 'value',
      yField: 'name',
      seriesField: 'name',
      // legend: {
      //   position: 'top-left',
      // },
      legend: false,
    });

    bar.render();
  }

  //课程热度
  courseHeat() {
    const data = [
      { name: 'AR 开发', value: 38 },
      { name: 'VR 开发', value: 52 },
      { name: 'Unity 开发', value: 61 },
      { name: '三维建模', value: 145 },
      { name: '全景设计', value: 48 },
    ];

    const bar = new Bar('container4', {
      data,
      xField: 'value',
      yField: 'name',
      seriesField: 'name',
      // legend: {
      //   position: 'top-left',
      // },
      legend: false,
    });

    bar.render();
  }

  courseUtilization() {
    const data = [
      { name: 'AR 开发', value: 38 },
      { name: 'VR 开发', value: 52 },
      { name: 'Unity 开发', value: 61 },
      { name: '三维建模', value: 145 },
      { name: '全景设计', value: 48 },
    ];

    const bar = new Bar('container13', {
      data,
      xField: 'value',
      yField: 'name',
      seriesField: 'name',
      // legend: {
      //   position: 'top-left',
      // },
      legend: false,
    });

    bar.render();
    return bar;
  }

  //课程访问总量
  courseTotalVisits() {
    const data = [
      { month: '一月', count: 38, },
      { month: '二月', count: 52, },
      { month: '三月', count: 61, },
      { month: '四月', count: 145, },
      { month: '五月', count: 48, },
      { month: '六月', count: 38, },
      { month: '七月', count: 38, },
      { month: '八月', count: 28, },
      { month: '九月', count: 38, },
      { month: '十月', count: 58, },
      { month: '十一月', count: 38, },
      { month: '十二月', count: 67, },
    ];

    const columnPlot = new Column('container5', {
      data,
      xField: 'month',
      yField: 'count',
      label: {
        // 可手动配置 label 数据标签位置
        position: 'middle', // 'top', 'bottom', 'middle',
        // 配置样式
        style: {
          fill: '#FFFFFF',
          opacity: 0.6,
        },
      },
      meta: {
        type: {
          alias: '类别',
        },
        sales: {
          alias: '销售额',
        },
      },
    });

    columnPlot.render();
    // return columnPlot;
  }

  innerProductGraph() {
    const data = [
      { month: '一月', value: 38, },
      { month: '二月', value: 52, },
      { month: '三月', value: 61, },
      { month: '四月', value: 145, },
      { month: '五月', value: 48, },
      { month: '六月', value: 38, },
      { month: '七月', value: 38, },
      { month: '八月', value: 28, },
      { month: '九月', value: 38, },
      { month: '十月', value: 58, },
      { month: '十一月', value: 38, },
      { month: '十二月', value: 67, },
    ];
    const chart = new Chart({
      container: 'container15',
      autoFit: true,
      height: 385,
    });
    chart.data(data);
    chart.scale({
      value: {
        min: 0,
        nice: true,
      },
      month: {
        range: [0, 1],
      },
    });
    chart.tooltip({
      showCrosshairs: true,
      shared: true,
    });

    chart.axis('value', {
      label: {
        formatter: (val) => {
          return (+val).toFixed();
        },
      },
    });

    chart.area().position('month*value');
    chart.line().position('month*value');

    chart.render();
  }


  DrawChinaDistrbutionMap() {
    var ROOT_PATH = 'https://cdn.jsdelivr.net/gh/apache/echarts-website@asf-site/examples';

    var chartDom = document.getElementById('map') as HTMLDivElement;
    var myChart = echarts.init(chartDom, null, { renderer: 'svg' });
    var option;
    myChart.showLoading();
    //const fontSize=this.GetScreenZoom()*0.8/100+"rem";
    $.get('./china.json', function (geoJson) {

      myChart.hideLoading();



      echarts.registerMap('Think', geoJson);
      option = {
        title: {
          text: '加速想象力学员分布',
          subtext: '加速想象力教学科技有限公司',
          sublink: 'https://http://edu.arvroffer.com/'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>{c} (人)'
        },
        // toolbox: {
        //   show: true,
        //   orient: 'vertical',
        //   left: 'right',
        //   top: 'center',
        //   feature: {
        //     dataView: { readOnly: false },
        //     restore: {},
        //     saveAsImage: {}
        //   }
        // },
        visualMap: {
          min: 0,
          max: 100,
          text: ['学员', ''],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['#ffffff', '#d9f2ff', '#a9d0f0', '#80b4de', '#5498cf']
          }
        },
        series: [
          {
            name: '加速想象力学员分布',
            type: 'map',
            mapType: 'Think', // 自定义扩展图表类型
            label: {
              show: true,
            },
            data: [
              { name: '新疆', value: 0 },//1
              { name: '西藏', value: 0 },//2
              { name: '内蒙古', value: 1 },//3
              { name: '青海', value: 57 },//4
              { name: '四川', value: 1 },//5
              { name: '黑龙江', value: 0 },//6
              { name: '甘肃', value: 70 },//7
              { name: '云南', value: 2 },//8
              { name: '广西', value: 0 },//9
              { name: '湖南', value: 0 },//10
              { name: '陕西', value: 358 },//11
              { name: '广东', value: 1 },//12
              { name: '河北', value: 1 },//13
              { name: '湖北', value: 1 },//14
              { name: '贵州', value: 0 },//15
              { name: '山东', value: 26 },//16
              { name: '江西', value: 0 },//17
              { name: '河南', value: 2 },//18
              { name: '辽宁', value: 0 },//19
              { name: '山西', value: 1 },//20
              { name: '安徽', value: 0 },//21
              { name: '福建', value: 1 },//22
              { name: '浙江', value: 1 },//23
              { name: '江苏', value: 1 },//24
              { name: '重庆', value: 0 },//25
              { name: '宁夏', value: 0 },//26
              { name: '海南', value: 0 },//27
              { name: '台湾', value: 0 },//28
              { name: '北京', value: 0 },//29
              { name: '天津', value: 0 },//30
              { name: '上海', value: 0 },//31
              { name: '香港', value: 0 },//32
              { name: '澳门', value: 0 },//33
              { name: '吉林', value: 0 },//34
            ],
            // 自定义名称映射
            nameMap: {
              // 'Central and Western': '中西区',
              // 'Eastern': '东区',
              // 'Islands': '离岛',
              // 'Kowloon City': '九龙城',
              // 'Kwai Tsing': '葵青',
              // 'Kwun Tong': '观塘',
              // 'North': '北区',
              // 'Sai Kung': '西贡',
              // 'Sha Tin': '沙田',
              // 'Sham Shui Po': '深水埗',
              // 'Southern': '南区',
              // 'Tai Po': '大埔',
              // 'Tsuen Wan': '荃湾',
              // 'Tuen Mun': '屯门',
              // 'Wan Chai': '湾仔',
              // 'Wong Tai Sin': '黄大仙',
              // 'Yau Tsim Mong': '油尖旺',
              // 'Yuen Long': '元朗'
            }
          }
        ]
      }
      myChart.setOption(option);

      option && myChart.setOption(option);
    })
    return myChart
  }

  RenderPicture = (props: IDraw) => {
    return <div className={props.className}>
      <div className="text">{props.title}</div>
      <div id={props.id} style={{ height: "100%", paddingTop: "20px" }} />
    </div>
  }

  render() {



    const {
      currentUser = {
        avatar: '',
        name: '',
      }
    } = this.props;
    return (
      <div id="home-back" className="home-back">
        <div className="home-header">
          <span>{` 欢迎回来，${currentUser.name}。`}</span>
          <div />
        </div>
        <div className="home-container">
          <div style={{ display: "flex", height: "49%" }}>
            <div id='map' className="home-map">
              {/* <img src="./FenBu.png" style={{width: "100%", height: "100%"}}/> */}
            </div>
            <div className="home-up-right">
              <div className="marginLeft" style={{ display: "flex", height: "40%" }}>
                <div className="home-today-visited">
                  <div className="text">今日访问</div>
                  <div style={{
                    paddingTop: 20,
                    display: "grid",
                    placeItems: "center",
                    height: "100%"
                  }}>
                    <div>
                      <div style={{ fontSize: 32, color: "#e88282" }}>9999
                      </div>
                      <div style={{ fontSize: 10, color: "#666666", textAlign: "center" }}>较昨日&nbsp;+140
                      </div>
                    </div>
                  </div>
                </div>
                <this.RenderPicture id={"container3"} title={"访问趋势"} className={"home-visited-trend marginLeft"} />
              </div>
              <div className="marginLeft" style={{ display: "flex", height: "56%" }}>
                <this.RenderPicture id={"container11"} title={"课程学习排行榜"} className={"home-course-top"} />
                <this.RenderPicture id={"container16"} title={"课程数量"} className={"home-course-count marginLeft"} />
              </div>
            </div>
          </div>
          <div style={{ display: "flex", height: "49%" }}>
            <div className="home-down-left">
              <this.RenderPicture id={"container4"} title={"课程热度"} className={"home-course-hot"} />
              <this.RenderPicture id={"container13"} title={"课程使用率"} className={"home-course-use"} />
            </div>
            <div className="home-down-right marginLeft">
              <this.RenderPicture id={"container15"} title={"课程访问量(总)"} className={"home-course-use-all"} />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(DashboardWorkplace);

